using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using mvcincode.Models;

namespace mvcincode.Controllers;


public class DocumentController : Controller
{
    private readonly IAuthorizationService _authorizationService;

    public DocumentController(IAuthorizationService authorizationService)
    {
        this._authorizationService = authorizationService;
    }

    public async Task<IActionResult> Index()
    {
        // 这里的资源可以是来自数据库中查询到的数据对象
        var document = new Document
        {
            Id = 1,
            Name = "深入浅出C#",
            Author = "Alan"
        };
        // 会去调指定的DocumentPolicy, 然后去调相应的Handler
        var authorizationResult = await _authorizationService.AuthorizeAsync(User, document, "DocumentPolicy");
        // var authorizationResult = await _authorizationService.AuthorizeAsync(User, document, Operations.Read);

        // 验证成功
        if (authorizationResult.Succeeded)
            return Content("document授权成功");
        // 用户已登录
        else if (User.Identity.IsAuthenticated)
            return new ForbidResult();
        // 否则用户还没有登录,就叫Challenge
        else
            return new ChallengeResult();
    }
}